﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;

namespace zszs
{
    public partial class FrmLogin : Form
    {

        public FrmLogin(HttpClient httpClient)
        {
            this.httpClient = httpClient;
            this.Text = "登陆";
            InitializeComponent();
        }
        private HttpClient httpClient;
        /// <summary>
        /// QQ号码
        /// </summary>
        private string qqAccount;
        /// <summary>
        /// 登陆后事件
        /// </summary>
        public event LoginCallback loginEvent;
        /// <summary>
        /// 设置文本 事件
        /// </summary>
        public event SetTextCallback setTextEvent;
        /// <summary>
        /// 是否登陆成功
        /// </summary>
        private bool isLoginSuc = false;
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            try
            {
                this.webBrowser1.Url = new Uri(VoteUrl.ADRESS_LOGIN + "&rx=" + DateTime.Now);
            }
            catch (Exception ex)
            {
                if (setTextEvent != null)
                {
                    setTextEvent("error:" + ex.Message);
                }
                this.Close();
            }
        }
        //地址改变前 事件.
        /// <summary>
        /// 地址改变前 事件.
        /// //http://php.qzone.qq.com/index.php?mod
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            try
            {
                Uri url = e.Url;
                string s = url.Query;
                if (string.IsNullOrEmpty(qqAccount))
                {
                    qqAccount = Regex.Match(s, "clientuin=(.|\n)*?&")
                       .Value.TrimStart("clientuin=".ToCharArray())
                       .TrimEnd('&');
                }
                string path = url.LocalPath;
                isLoginSuc = false;
                if (path == "/index.php")//成功登陆
                {
                    this.webBrowser1.Document.Encoding = "gb2312";
                    //添加 cookie
                    if (this.webBrowser1.Document != null && this.webBrowser1.Document.Cookie != null)
                    {
                        httpClient.Cookies = GetCookie(this.webBrowser1.Document.Cookie, url,
                           new Uri(VoteUrl.ADRESS_BASEQZONE), new Uri(VoteUrl.ADRESS_WQZONE),
                           new Uri(VoteUrl.ADRESS_TAOTAO));
                    }
                    httpClient.Cookies.Add(url, new Cookie("x", "xx"));
                    string[] urls = new string[] { "http://php.qzone.qq.com/index.php?mod=portal&act=genkey",
                        "http://php.qzone.qq.com/index.php?mod",
                        "http://comment5.qq.com/i_comment.htm","http://comment5.qq.com/axel/cookie.htm",
                        "http://comment5.qq.com/i_login31.htm?b_login_frame&&true",
                        "http://comment5.qq.com/php/greplyBycid.php?site=mag&c_id=27"
                    };
                    for (int i = 0; i < urls.Length; i++)
                    {
                        string result = httpClient.DownloadString(urls[i]);
                        string cookieHeader = httpClient.Cookies.GetCookieHeader(new Uri(urls[i]));
                    }
                    Cookie qqUin = httpClient.Cookies.GetCookies(url)["zzpaneluin"];//"comment_uin";//605064709 寻找风的感觉
                    if (qqUin == null)
                    {
                        qqUin = httpClient.Cookies.GetCookies(url)["uin"];
                    }
                    if (qqUin != null)
                    {
                        string login_nickname = Regex.Replace(qqUin.Value, "^o(0)*", "");
                        if (string.IsNullOrEmpty(qqAccount))
                        {
                            qqAccount = login_nickname;
                        }
                    }
                    isLoginSuc = true;
                    this.webBrowser1.Stop();
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                if (setTextEvent != null)
                {
                    setTextEvent("error:" + ex.Message);
                }
                this.Close();
            }

        }
        //获取 CookieContainer
        /// <summary>
        /// 获取 CookieContainer
        /// </summary>
        /// <param name="cookieStr"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private CookieContainer GetCookie(string cookieStr, Uri url, Uri url2, Uri url3, Uri ur4)
        {
            CookieContainer myCookieContainer = new CookieContainer();
            myCookieContainer.PerDomainCapacity = 200;
            string[] cookstr = cookieStr.Split(';');
            foreach (string str in cookstr)
            {
                string[] cookieNameValue = str.Split('=');
                string value = "";
                for (int i = 1; i < cookieNameValue.Length; i++)
                {
                    value += cookieNameValue[i].Trim() + "=";
                }
                value = value.TrimEnd('=');

                Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(),
                    value.Replace(",", "%2C"));
                ck.Domain = "qq.com";
                myCookieContainer.Add(url, ck);
                if (url2 != null && url3 != null && ur4 != null)
                {
                    myCookieContainer.Add(url2, ck);
                    myCookieContainer.Add(url3, ck);
                    myCookieContainer.Add(ur4, ck);
                }

            }
            return myCookieContainer;
        }

        private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (loginEvent != null)
            {
                loginEvent(isLoginSuc, qqAccount);
            }
        }

        private void lklblCancel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Close();
        }
    }
}
